package otherPractice;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.CountDownLatch;

/**
 * 模拟高并发
 */
public class HighConcurrenceUtill {

    static int successNum = 0;
    static int failNum = 0;

    public static void main(String[] args) {
        CountDownLatch downLatch = new CountDownLatch(1);
        for(int i =0;i< 10000; i++){
            new Thread(new Runnable() {
                public void run() {
                    try {
                        System.out.println(Thread.currentThread().getName() + "线程创建,等待执行getTest()");
                        downLatch.await();

                        //System.out.println(Thread.currentThread().getName() + "线程开始执行getTest()");
                        getTest();
                        System.out.println(Thread.currentThread().getName() + "线程执行结束");
                        System.out.println("请求成功次数为" + successNum + "----失败次数为" + failNum);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
            downLatch.countDown();
        }


        System.out.println("请求成功次数为" + successNum + "----失败次数为" + failNum);
    }


    public static void getTest(){
        try {
            String addressUrl = "http://192.168.6.186:8080/banyechan_tomcat_war/index/home";
            //String addressUrl = "https://www.baidu.com/";
            URL url = new URL(addressUrl);
            //得到connection对象。
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            //设置请求方式
            connection.setRequestMethod("GET");
            //连接
            connection.connect();

            //得到响应码
            int responseCode = connection.getResponseCode();
            //System.out.println("----  responseCode= " + responseCode);
            if(responseCode == HttpURLConnection.HTTP_OK){
                //得到响应流
                InputStream inputStream = connection.getInputStream();
                connection.getResponseMessage();
                //System.out.println("--- connection.getResponseMessage()=   --" + connection.getResponseMessage());
                StringBuilder sb = new StringBuilder("响应内容=");
                byte[] b = new byte[1024];
                int len = 0;
                while ((len = inputStream.read(b)) != -1){
                    sb.append(new String(b, 0, len, "utf-8"));
                }
                inputStream.close();
                connection.disconnect();
                System.out.println("---   result = ---- 访问成功！！！！**" + sb.toString());
                successNum = successNum + 1;
            }else {
                System.out.println("--- 访问失败，code=" + responseCode);
                failNum = failNum + 1;
            }
        } catch (Exception e) {
            failNum = failNum + 1;
            e.printStackTrace();
        }
    }


}
